'use strict';

const RouterService = require('../base');
const { Op } = require('sequelize');
class MonthlyBiddingService extends RouterService {
  static get modelName() {
    return 'Business.MonthlyBidding';
  }

  getPageInclude() {
    return [
      {
        model: this.ctx.model.Business.Dish,
        as: 'dishList',
        order: [
          ['category', 'ASC']
        ]
      },
      {
        model: this.ctx.model.Business.BiddingSupplier,
        as: 'biddingSupplierList'
      },
      {
        model: this.ctx.model.Business.Supplier,
        as: 'supplier'
      }
    ]
  }
  getListInclude() {
    return this.getPageInclude();
  }
  getDetailInclude() {
    return this.getPageInclude();
  }

  async beforeCreate(data) {
    const { month } = data

    // 只能存在一个相同月
    const count = await this.ctx.model.Business.MonthlyBidding.count({
      where: {
        month
      }
    })
    if (count > 0) {
      throw new Error('该月份已存在比价记录')
    }
    return true
  }

  async beforeUpdate(id, data) {
    const { month } = data
    const count = await this.ctx.model.Business.MonthlyBidding.count({
      where: {
        month,
        id: {
          [Op.ne]: id
        }
      }
    })
    if (count > 0) {
      throw new Error('该月份已存在比价记录')
    }
    return true
  }

  async submitSupplier(id, selected_supplier_id) {
    const monthlyBidding = await this.ctx.model.Business.MonthlyBidding.findByPk(id);
    if (!monthlyBidding) {
      throw new Error('比价项目不存在');
    }
    // 判断daily_menu表中是否存在该月份的采购单
    const dailyMenu = await this.ctx.model.Business.DailyMenu.findOne({
      where: {
        monthly_bidding_id: id
      }
    })
    if (dailyMenu) {
      throw new Error('该月份已存在采购单，如需切换入围供应商，请先删除采购单');
    }
    return await this.ctx.model.Business.MonthlyBidding.update({
      selected_supplier_id,
      status: 3
    }, {
      where: {
        id
      }
    })
  }

  /**
   * Soft delete record
   * @param {String|Number} id
   * @param {String|Number} userId
   */
  async delete(id) {
    const model = await this.findById(id);
    if (!model) {
      throw new Error('删除对象不存在')
    }
    console.log('删除')
    const dailyMenu = await this.ctx.model.Business.DailyMenu.findAll({
      where: {
        monthly_bidding_id: id
      }
    })
    // 创建事务，删除比价项目时，删除dish、删除所有供应商报价、删除菜单、菜单明细
    const transaction = await this.ctx.model.transaction();
    try {
      await this.ctx.model.Business.MonthlyBidding.destroy({
        where: {
          id
        },
        transaction
      })
      await this.ctx.model.Business.Dish.destroy({
        where: {
          monthly_bidding_id: id
        },
        transaction
      })
      await this.ctx.model.Business.SupplierQuote.destroy({
        where: {
          monthly_bidding_id: id
        },
        transaction
      })
      await this.ctx.model.Business.BiddingSupplier.destroy({
        where: {
          monthly_bidding_id: id
        },
        transaction
      })
      await this.ctx.model.Business.DailyMenu.destroy({
        where: {
          monthly_bidding_id: id
        },
        transaction
      })
      await this.ctx.model.Business.DailyMenuItem.destroy({
        where: {
          daily_menu_id: {
            [Op.in]: dailyMenu.map(item => item.id)
          }
        },
        transaction
      })
      await transaction.commit();
      return true;
    } catch (error) {
      console.log('error',error)
      await transaction.rollback();
      throw error;
    }
  }
}

module.exports = MonthlyBiddingService;
